﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Xps.Serialization;

using System.Diagnostics;
using System.Threading;

namespace SuperKit {
    class FastUnpackExe : CommandExecutor {
        const string DEFAULT_DIR = "(_UNPACK)";

        string destFile;
        bool isOverride;
        private List<FileInfo> Files { get; set; }
        private string DestDir { get; set; }

        public FastUnpackExe(ArgReader arg, IExecutorOwner form, string fpath) : base(arg, form, fpath) {
            isOverride = arg.IsContain("-override");
        }

        public override void Execute() {
            Thread t = new Thread(OnProcess);
            t.Start();
        }

        private void OnProcess() {
            if (Directory.Exists(FilePath)) {
                DestDir = GetDestDir(DEFAULT_DIR);
                Files = Kit.GetAllFiles(null, new DirectoryInfo(FilePath), Kit.PAK_EXTS);
                foreach (var i in Files) {
                    string save_path = Path.Combine(DestDir, Path.GetFileNameWithoutExtension(i.Name));
                    Unpack(i.FullName, save_path);
                }
            } else if (File.Exists(FilePath)) {
                FileInfo fileInfo = new(FilePath);
                string unpack_path = Path.Combine(fileInfo.DirectoryName, Path.GetFileNameWithoutExtension(fileInfo.Name));
                Unpack(FilePath, Kit.IsEmpty(TargetDir) ? unpack_path : TargetDir);
            }

            End();
        }

        private void Unpack(string filename, string dir) {
            string overrideString = isOverride ? "True" : "False";
            Flush("Unpack: {0} => {1}", filename, dir);

            string script_args = $"-unpack \"{filename}\" -o \"{dir}\" -override {overrideString}";
            Flush("{0} {1}", FastPackExe.FAST_PACK_PY, script_args);
            FastPackExe.RunPythonScript(FastPackExe.FAST_PACK_PY, script_args);
        }
    }
}
